package org.suze.springboot.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description: 方法耗时拦截器
 * @Date : 下午7:18 2017/9/18
 * @Author : 石冬冬-Heil Hitler(dongdong.shi@mljr.com)
 */
public class TimerInterceptor extends HandlerInterceptorAdapter {

    private static final Logger LOGGER = LoggerFactory.getLogger(TimerInterceptor.class);
    private final NamedThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>("StopWatch-StartTime");


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long beginTime = System.currentTimeMillis();//1、开始时间
        startTimeThreadLocal.set(beginTime);//线程绑定变量（该数据只有当前请求的线程可见）
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            MethodParameter[] methodParameters = handlerMethod.getMethodParameters();
            StringBuffer ms = new StringBuffer();
            for(MethodParameter methodParameter : methodParameters){
                String param = methodParameter.getParameterName();
                Object value = request.getParameter(param);
                ms.append(param).append(":[").append(value).append("]").append(",");
            }
            LOGGER.info("show method params:{}",ms.toString());
        }
        return true;//继续流程
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        long endTime = System.currentTimeMillis();//2、结束时间
        long beginTime = startTimeThreadLocal.get();//得到线程绑定的局部变量（开始时间）
        long consumeTime = endTime - beginTime;//3、消耗的时间
        if(consumeTime > 500) {//此处认为处理时间超过500毫秒的请求为慢请求
            LOGGER.info(String.format("%s [cost gt 500ms] consume %d millis", request.getRequestURI(), consumeTime));
        }else{
            LOGGER.info(String.format("%s [cost le 500ms] consume %d millis", request.getRequestURI(), consumeTime));
        }
    }
}
